package com.hmdp.service.impl;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmdp.dto.RedisData;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IShopService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.CacheClient;
import com.hmdp.utils.SystemConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.GeoResult;
import org.springframework.data.geo.GeoResults;
import org.springframework.data.redis.connection.RedisGeoCommands;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.domain.geo.GeoReference;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private CacheClient cacheClient;

    //线程池对象
    private static final ExecutorService CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(10);

    @Override
    public Result queryById(Long id) {
        //缓存穿透解决方案
//        Shop shop = cacheClient.queryWithPassThrough(id, CACHE_SHOP_KEY, Shop.class, this::getById, CACHE_SHOP_TTL, TimeUnit.MINUTES);

        //利用互斥锁解决缓存击穿问题
        Shop shop = queryWithMutex(id);

        //利用逻辑过期解决缓存击穿问题
//        Shop shop = queryWithLogicalExpire(id);
//        Shop shop = cacheClient.queryWithLogicalExpire(id, CACHE_SHOP_KEY, Shop.class, this::getById, 10L, TimeUnit.SECONDS);

        if (shop == null) {
            return Result.fail("查询的商铺数据不存在！");
        }
        return Result.ok(shop);
    }

    @Transactional
    @Override
    public Result updateShopDataById(Shop shop) {
        Long id = shop.getId();
        if (id == null) {
            return Result.fail("商品id不能为空！");
        }
        String key = CACHE_SHOP_KEY + id;
        // 写入数据库
        updateById(shop);
        //删除缓存
        stringRedisTemplate.delete(key);
        return Result.ok();
    }

    @Override
    public Result queryShopByType(Integer typeId, Integer current, Double x, Double y) {
        //1.若坐标为空，只做分页查询
        if (x == null || y == null) {
            // 根据类型分页查询
            Page<Shop> page = this.query()
                    .eq("type_id", typeId)
                    .page(new Page<>(current, SystemConstants.DEFAULT_PAGE_SIZE));
            // 返回数据
            return Result.ok(page.getRecords());
        }

        //2.获取分页参数
        int from = (current - 1) * SystemConstants.DEFAULT_PAGE_SIZE;
        int end = current * SystemConstants.DEFAULT_PAGE_SIZE;

        //3.GeoSearch shop:geo:1 fromlonlat x y 5000 m withdist
        String key = SHOP_GEO_KEY + typeId;
        /*
            GeoResults: 是一个容器类，用于存储一组GeoResult对象
                        可使用getContent()方法获取GeoResult对象集合
         */
        GeoResults<RedisGeoCommands.GeoLocation<String>> results = stringRedisTemplate.opsForGeo().search(
                key,
                GeoReference.fromCoordinate(x, y),
                new Distance(5000),
                RedisGeoCommands.GeoSearchCommandArgs.newGeoSearchArgs().includeDistance().limit(end)
        );
        /*
            GeoResult: 代表单个地理空间查询的结果项 用于存储一个RedisGeoCommands.GeoLocation对象
                      包含以下部分：
                        GeoLocation：表示地理位置的信息，包括名称（通常是店铺ID）和坐标（经纬度）
                        Distance：表示该位置与查询中心点之间的距离（如果查询时指定了要返回距离）
                       可使用getContent()方法获取RedisGeoCommands.GeoLocation对象
         */
        List<GeoResult<RedisGeoCommands.GeoLocation<String>>> list = results.getContent();
        if (list.isEmpty()){
            return Result.ok(Collections.emptyList());
        }
        if (list.size() <= from){
            // 没有下一页了，结束
            return Result.ok(Collections.emptyList());
        }
        //4.根据分页起始参数跳过部分数据  获取店铺信息
        List<Long> shopIdList = new ArrayList<>();
        Map<String,Double> distanceMap = new HashMap<>();
        list.stream().skip(from).forEach(result -> {
            /*
                RedisGeoCommands.GeoLocation: 表示一个地理位置，通常包含以下信息：
                    name: 地理位置的名称，通常是ID 即member
                    point: 地理位置的坐标，即经纬度
             */
            RedisGeoCommands.GeoLocation<String> geoLocation = result.getContent();
            Distance distance = result.getDistance();
            shopIdList.add(Long.valueOf(geoLocation.getName()));
            distanceMap.put(geoLocation.getName(), distance.getValue());
        });
        // 5.根据id查询Shop
        String idStr = StrUtil.join(",", shopIdList);
        List<Shop> shops = query().in("id", shopIdList).last("ORDER BY FIELD(id," + idStr + ")").list();
        shops.forEach(shop -> {
            shop.setDistance(distanceMap.get(shop.getId().toString()));
        });
        return Result.ok(shops);
    }

    public Shop queryWithPassThrough(Long id) {
        String key = CACHE_SHOP_KEY + id;
        //从缓存中获取数据
        String cacheShopData = stringRedisTemplate.opsForValue().get(key);
        if (StrUtil.isNotBlank(cacheShopData)) {
            //1.若缓存中有数据，则从缓存中获取数据
            Shop shop = JSON.parseObject(cacheShopData, Shop.class);
            return shop;
        }
        //若从缓存中获取的值是空值，说明是不存在的数据
        if (cacheShopData != null) {
            return null;
        }
        //2.从数据库中获取数据，同步到缓存中
        Shop data = this.getById(id);
        if (data == null) {
            //解决缓存穿透：当数据库查不到数据时，向缓存中设置空值即可
            stringRedisTemplate.opsForValue().set(key,"",CACHE_NULL_TTL,TimeUnit.MINUTES);
            return null;
        }
        stringRedisTemplate.opsForValue().set(key,JSON.toJSONString(data),CACHE_SHOP_TTL, TimeUnit.MINUTES);
        return data;
    }

    public Shop queryWithMutex(Long id) {
        String key = CACHE_SHOP_KEY + id;
        //从缓存中获取数据
        String cacheShopData = stringRedisTemplate.opsForValue().get(key);
        if (StrUtil.isNotBlank(cacheShopData)) {
            //1.若缓存中有数据，则从缓存中获取数据
            Shop shop = JSON.parseObject(cacheShopData, Shop.class);
            return shop;
        }
        //若从缓存中获取的值是空值，说明是不存在的数据
        if (cacheShopData != null) {
            return null;
        }

        //从缓存获取数据为空，则获取互斥锁
        String lockKey = LOCK_SHOP_KEY + id;
        Shop data = null;
        try {
            boolean flag = tryLock(lockKey);
            if (!flag) {
                // 获取失败，休眠后重试
                Thread.sleep(50);
                return queryWithMutex(id);
            }

            //获取互斥锁后，查数据库将数据同步到缓存中
            //2.从数据库中获取数据，同步到缓存中
            data = this.getById(id);
            //这里进行doubleCheck，再次查缓存是否有数据，有则无需同步，直接返回数据即可!
            cacheShopData = stringRedisTemplate.opsForValue().get(key);
            if (StrUtil.isNotBlank(cacheShopData)) {
                //若缓存中有数据，则从缓存中获取数据
                Shop shop = JSON.parseObject(cacheShopData, Shop.class);
                return shop;
            }

            //这里模拟复杂业务重建缓存，增加耗时
            Thread.sleep(200);
            if (data == null) {
                //解决缓存穿透：当数据库查不到数据时，向缓存中设置空值即可
                stringRedisTemplate.opsForValue().set(key,"",CACHE_NULL_TTL,TimeUnit.MINUTES);
                return null;
            }
            stringRedisTemplate.opsForValue().set(key,JSON.toJSONString(data),CACHE_SHOP_TTL, TimeUnit.MINUTES);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }finally {
            //同步完成后，释放锁
            unlock(lockKey);
        }
        return data;
    }

    private Shop queryWithLogicalExpire(Long id) {
        String key = CACHE_SHOP_KEY + id;
        //从缓存中获取数据
        String cacheShopData = stringRedisTemplate.opsForValue().get(key);
        if (StringUtils.isBlank(cacheShopData)){
            //若缓存中不存在，则直接返回null
            return null;
        }
        //若缓存中存在数据，则取出value判断数据是否过期
        RedisData redisData = JSON.parseObject(cacheShopData, RedisData.class);
        Shop shop = JSON.parseObject(redisData.getData().toString(), Shop.class);//缓存数据
        LocalDateTime expireTime = redisData.getExpireTime();
        if (expireTime.isAfter(LocalDateTime.now())){
            //若缓存的数据未过期，则返回缓存数据即可
            return shop;
        }
        //若缓存数据已过期，则获取互斥锁并开启新线程(新线程异步重建缓存数据)，然后返回旧数据。
        String lockKey = LOCK_SHOP_KEY + id;
        if (tryLock(lockKey)){
            //这里进行doubleCheck 获取缓存并判断是否过期，若未过期则无需重建缓存
            String cacheShopData2 = stringRedisTemplate.opsForValue().get(key);
            RedisData redisData2 = JSON.parseObject(cacheShopData2, RedisData.class);
            shop = JSON.parseObject(redisData2.getData().toString(), Shop.class);//缓存数据
            LocalDateTime expireTime2 = redisData.getExpireTime();
            if (expireTime2.isAfter(LocalDateTime.now())){
                //若缓存的数据未过期，则返回缓存数据即可
                return shop;
            }
            CACHE_REBUILD_EXECUTOR.submit(() -> {
                try {
                    //重建缓存
                    //手动设置休眠，模拟复杂业务重建的高耗时
                    Thread.sleep(200);
                    saveShop2Redis(id,20L);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                } finally {
                    //释放锁
                    unlock(lockKey);
                }
            });
        }
        return shop;
    }


    //获取互斥锁
    public Boolean tryLock(String key){
        Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(key, "1",LOCK_SHOP_TTL,TimeUnit.MINUTES);
        return BooleanUtil.isTrue(flag);
    }

    //释放锁
    public void unlock(String key){
        stringRedisTemplate.delete(key);
    }

    //重建缓存方法
    public void saveShop2Redis(Long id,Long expireSeconds){
        String key = CACHE_SHOP_KEY + id;
        //1.查询数据库获取数据
        Shop shop = this.getById(id);
        //2.重建缓存
        RedisData redisData = new RedisData();
        redisData.setData(shop);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(expireSeconds));
        stringRedisTemplate.opsForValue().set(key,JSON.toJSONString(redisData));
    }


    public static int num = 5;

    public static void main(String[] args) {
        System.out.println(test01());
    }


    public static String test01(){
        try {
            return test02();
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            System.out.println("execute finally!!");
        }
    }

    public static String test02(){
        if (num > 0){
            num--;
            return test02();
        }
        System.out.println("-----test02-----");
        return "ok!";
    }
}
